package com.gimi.cloud.jimi.client.service.userInfo.impl;

import com.gimi.cloud.jimi.client.service.userInfo.EmergencyContactService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.dao.dao.userInfo.EmergencyContactDao;
import com.gimi.cloud.jimi.dto.userInfo.RdEmergencyContactDTO;
import com.gimi.cloud.jimi.entity.userInfo.RdEmergencyContact;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class EmergencyContactServiceImpl implements EmergencyContactService {

    @Autowired
    private EmergencyContactDao emergencyContactDao;

    @Override
    public void saveEmergencyContact(RdEmergencyContactDTO param) {
        RdEmergencyContact record = new RdEmergencyContact();
        //TODO 有效期
        try {
            param.setReportEffectionEnd(DateUtil.strtoDate("2099-01-01","yyyy-MM-dd"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(param, record);
        int code = emergencyContactDao.baseInsert(record);
        if (code <= 0) {
            throw new MsgException(ResponseCodeEnum.INVALID);
        }
    }

    @Override
    public RdEmergencyContactDTO findEmergencyContactByUser(RdEmergencyContactDTO param) {
        Integer userId = param.getUserId();
        List<RdEmergencyContact> list = emergencyContactDao.findByUser(userId);
        if(list != null && list.size() > 0) {
            RdEmergencyContact ec = list.get(0);
            RdEmergencyContactDTO ecDto = new RdEmergencyContactDTO();
            BeanUtils.copyProperties(ec, ecDto);
            return ecDto;
        }
        return null;
    }

	@Override
	public Map<String, Object> getAuthenticationInfo(Integer userId) {
		Map<String, Object> map = new HashMap<>();
		List<RdEmergencyContact> user = emergencyContactDao.findByUser(userId);
		//无数据
		if (user == null || user.size() == 0) {
			map.put("status", 0);
			return map;
		}
		List<RdEmergencyContactDTO> list = emergencyContactDao.isEffection(userId);
		//有数据未过期
		if (user != null && list!= null && list.size() > 0) {
			map.put("status", 1);
			map.put("data", list);
			return map;
		}else {
			map.put("status", 2);
			return map;
		}
		
	}
}
